package com.tian.netty.core;


import com.alibaba.fastjson.JSON;
import com.tian.netty.message.ChargerCommLog;
import com.tian.netty.message.LogType;
import com.tian.netty.util.JConverter;
import com.tian.netty.util.Utility;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
//import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * 2023年11月05日 22:59
 * 在线刷题 1200+题和1000+篇干货文章：<a href="https://woaijava.cc/">博客地址</a>
 * <p>
 *  用于处理从客户端接收到的消息
 */
public class MsgInBoundHandler extends SimpleChannelInboundHandler<byte[]> {
    
    private static final Logger logger = LoggerFactory.getLogger(MsgInBoundHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] msgObject) throws Exception {
        //接收到的客户端消息
        logger.info("C(" + (ctx.channel().remoteAddress()) + " ==>>S:" + JConverter.bytes2String(msgObject));
        ReqDispatcher.submit((SocketChannel)ctx.channel(), msgObject);
    }
    
    /*
     * 在channel被启用的时候触发 (在建立连接的时候)
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {  
        logger.info("Client : " + ctx.channel().remoteAddress() + " active !");
    }
    
    /*
     * 在channel断开的时候触发 
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("Client : " + ctx.channel().remoteAddress() + " inactive !");
        //连接关闭后，清理系统资源
        String chargerNo = ClientChannelMap.getChargerNo(ctx.channel().id().asLongText());
        if (chargerNo != null && !"".equals(chargerNo.trim())) {
            ClientChannelMap.remove(chargerNo);
            //设备离线
            RedissonClient redissonClient=  Utility.getBean(RedissonClient.class);
            RBucket<String> bucket = redissonClient.getBucket("charger.online_" + chargerNo);
            ChargerCommLog chargerCommLog = new ChargerCommLog();
            chargerCommLog.setChargerCode(chargerNo);
            chargerCommLog.setLogType(LogType.OFFLINE);
            chargerCommLog.setLogTime(new Date());
            chargerCommLog.setParams("client:" + ctx.channel().remoteAddress());
            bucket.set(JSON.toJSONString(chargerCommLog));
        }
    }
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    }

    /*
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("channel is exception over.(SocketChannel)ctx.channel()=" + (SocketChannel)ctx.channel(), cause);
    } 
}
